﻿package net.wangit.adm.org;

import net.wangit.Unit;
import net.wangit.context.ActionContext;
import net.wangit.context.ActionContextHelper;
import net.wangit.context.LocalContext;
import net.wangit.support.UnitInterceptor;
import net.wangit.user.org.Org;
import net.wangit.user.org.OrgFactory;
import net.wangit.util.Checker;
import net.wangit.view.tree.Tree;
import net.wangit.view.unit.UnitComponent;

public class OrgRoleUI implements UnitInterceptor {

	public static final String ORGANIZATION_ID = "net.wangit.adm.org.OrgRoleUI.orgid";

	public OrgRoleUI() {
	}

	public String intercept(ActionContext ac, Unit unit) throws Exception {
		String oid = getAndSetOrganizationId();
		if (Checker.isEmpty(oid)) {
			return "";
		} else {
			unit.getElement("orgid").setDefaultValue(oid);
			Org organization = OrgFactory.getOrg(oid);
			Tree tree = (Tree) unit.getElement("roles").getObject();
			unit.getElement("count").setName(
					(new StringBuilder("(")).append(
							organization.getRoles().length).append("/").append(
							tree.size()).append(")").toString());
			unit.setTitle((new StringBuilder(String
					.valueOf(((UnitComponent) unit).getTitle()))).append(" - ")
					.append(organization.getName()).append("(").append(oid)
					.append(")").toString());
			return unit.write(ac);
		}
	}

	public static String getOrganizationId(ActionContext ac) {
		return (String) ac
				.getSessionAttribute("net.wangit.adm.org.OrgRoleUI.orgid");
	}

	public static String getAndSetOrganizationId() {
		ActionContext ac = LocalContext.getLocalContext().getActionContext();
		return ActionContextHelper.getRequest2Session(ac, "orgid",
				"net.wangit.adm.org.OrgRoleUI.orgid", null);
	}
}
